package com.goldgov.kduck.config;

import com.goldgov.kduck.locator.GatewayRoute;
import com.goldgov.kduck.locator.JdbcRouteLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @author guor
 */
@Component
@Primary
public class SwaggerProvider implements SwaggerResourcesProvider {
    Logger logger= LoggerFactory.getLogger(SwaggerProvider.class);
    private JdbcRouteLocator jdbcRouteLocator;

    public SwaggerProvider() {
    }

    @Autowired
    public SwaggerProvider(JdbcRouteLocator jdbcRouteLocator) {
        this.jdbcRouteLocator = jdbcRouteLocator;
    }
    @Override
    public List<SwaggerResource> get() {
        //获取所有router
        List<SwaggerResource> resources = new ArrayList<>();
        List<GatewayRoute> routes = jdbcRouteLocator.getRouteList();
        logger.info("Route Size:{}",routes.size());
        for (GatewayRoute route:routes) {
            resources.add(swaggerResource(route.getRouteName(), route.getPath().replace("**", "v2/api-docs")));
        }
//        resources.add(swaggerResource("gateway","http://localhost:8080/sso/v2/api-docs"));
        return resources;
    }
    private SwaggerResource swaggerResource(String name, String location) {
        logger.info("name:{},location:{}",name,location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}
